package com.study.cloud.gateway.core.filter.loadBalance;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.study.cloud.gateway.common.enums.ResponseCode;
import com.study.cloud.gateway.common.exception.InstanceNotFoundException;
import com.study.cloud.gateway.common.rule.DynamicConfigManager;
import com.study.cloud.gateway.common.rule.ServiceInstance;
import com.study.cloud.gateway.core.context.GatewayContext;
import lombok.extern.slf4j.Slf4j;


import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 负载均衡处理器 -- 随机
 * @author wangwancheng
 * @create 2025/7/20 17:13
 */
@Slf4j
public class RandomLoadBalanceRule implements IGatewayLoadBalanceRule {

    //单例模式
    private RandomLoadBalanceRule(){}
    private static class SingletonHolder {
        private static final RandomLoadBalanceRule INSTANCE = new RandomLoadBalanceRule();
    }
    public static RandomLoadBalanceRule getInstance() {
        return SingletonHolder.INSTANCE;
    }

    @Override
    public ServiceInstance choose(GatewayContext gatewayContext) {
        String uniqueId = gatewayContext.getUniqueId();
        return choose(uniqueId);
    }

    @Override
    public ServiceInstance choose(String uniqueId) {
        Set<ServiceInstance> serviceInstances = DynamicConfigManager.getInstance().getServiceInstances(uniqueId);
        if (CollectionUtils.isEmpty(serviceInstances)){
            log.error("not found serviceInstances");
            throw new InstanceNotFoundException(ResponseCode.SERVICE_INSTANCE_NOT_FOUND);
        }
        List<ServiceInstance> instances = new ArrayList<>(serviceInstances);
        //随机
        int index = ThreadLocalRandom.current().nextInt(instances.size());
        return instances.get(index);
    }
}
